package main

import (
	"encoding/json"
	"flag"
	"gitee.com/dashengbuqi/luckdraw/components"
	"gitee.com/dashengbuqi/luckdraw/models"
	"log"
	"net/http"
	"path/filepath"
	"runtime"
	"runtime/debug"
	"strconv"
	"strings"
)

var (
	addr = flag.String("addr", ":9090", "http service address")
	sept = GetSeparator()
	html = CurDir() + sept + "html"

	osType = runtime.GOOS
)

var hub *components.Hub

func CurDir() string {
	_, filename, _, _ := runtime.Caller(1)
	return filepath.Dir(filename)
}

func GetSeparator() string {
	if osType == "windows" {
		return "\\"
	} else if osType == "linux" {
		return "/"
	}
	return "/"
}

//活动首页
func home(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, html+sept+"index.html")
}

//活动首页
func message(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, html+sept+"message/index.html")
}

//获取有效用户及奖品
func list(w http.ResponseWriter, r *http.Request) {
	user := components.GetAllUserPool()
	pz := models.FindDrawLevel()
	result := make(map[string]interface{})
	result["users"] = user
	result["prize"] = pz
	j, _ := json.Marshal(result)
	w.Write(j)
}

//已获奖用户
func luck(w http.ResponseWriter, r *http.Request) {
	u := components.GetDrawnPool()
	j, _ := json.Marshal(u)
	w.Write(j)
}

//发送弹幕
func barrage(w http.ResponseWriter, r *http.Request) {
	body := r.PostFormValue("message")
	rs := `{"status":0,"msg":"未获取到弹幕内容"}`
	if len(body) > 0 {
		rs = `{"status":1,"msg":"发送成功"}`
		hub.Produce([]byte(body))
	}
	w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
	w.Header().Set("content-type", "application/json")             //返回数据格式是json
	w.Write([]byte(rs))
}

//废弃重抽
func discard(w http.ResponseWriter, r *http.Request) {
	num := r.PostFormValue("num")
	numInt, _ := strconv.Atoi(num)
	err := components.Discard(numInt)
	rs := `{"status":1,"msg":""}`
	if err != nil {
		rs = `{"status":0,"msg:"` + err.Error() + `"}`
	}
	w.Write([]byte(rs))
}

//抽奖
func draw(w http.ResponseWriter, r *http.Request) {
	nums := r.PostFormValue("nums")
	rs := `{"status":1,"msg":""}`
	if len(nums) == 0 {
		rs = `{"status":0,"msg:"未找到获奖名单"}`
	} else {
		numberStr := strings.Split(nums, ",")
		var numberArr []int
		if len(numberStr) > 0 {
			for _, num := range numberStr {
				i, _ := strconv.Atoi(num)
				numberArr = append(numberArr, i)
			}
		}
		result := components.Drawn(numberArr)

		if result != nil {
			rs = `{"status":0,"msg:"` + result.Error() + `"}`
		}
	}
	w.Write([]byte(rs))
}

func main() {
	PrintErrStack()

	log.Println("SERVER START ...")
	//flag.Parse()
	hub = components.NewHub()

	//监控用户连接
	go hub.Run()
	//消费队列数据
	go hub.Consume()
	h := http.FileServer(http.Dir(html + "/static"))
	http.Handle("/static/", http.StripPrefix("/static/", h))
	http.HandleFunc("/", home)
	http.HandleFunc("/list", list)          //当前奖项及未获奖用户
	http.HandleFunc("/luck", luck)          //已获奖用户 幸运用户
	http.HandleFunc("/index.html", message) //弹幕
	http.HandleFunc("/barrage", barrage)    //弹幕
	http.HandleFunc("/draw", draw)          //抽奖
	http.HandleFunc("/discard", discard)    //当前用户作废

	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		components.ServeWs(hub, w, r)
	})
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Printf("ListenAndServe:%v", err)
		panic(err)
	}
}

//打印错误
func PrintErrStack() {
	defer func() {
		if r := recover(); r != nil {
			var ok bool
			_, ok = r.(error)
			if !ok {
				log.Println("error")
				debug.PrintStack()
			}
		}
	}()
}
